package com.zuijin.demo.interceptor;

import com.alibaba.fastjson2.JSON;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "queryCursor", args = {MappedStatement.class, Object.class, RowBounds.class}),
})
public class MyExecutorInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("MyExecutorInterceptor");
        System.out.println(invocation.getMethod().getName());
        // 获取被拦截的方法的参数
        Object[] args = invocation.getArgs();

        // 获取 MappedStatement 对象
        MappedStatement mappedStatement = (MappedStatement) args[0];

        // 获取 SQL 语句和参数
        BoundSql boundSql = mappedStatement.getBoundSql(args[1]);
        String sql = boundSql.getSql();
        String jsonString = JSON.toJSONString(boundSql);
        System.out.println(jsonString);
        Object parameterObject = args[1];

        // 打印 SQL 语句和参数信息
        //System.out.println("Executing SQL: " + sql);
        //System.out.println("Parameters: " + JSON.toJSON(parameterObject));
        // TODO 获取sql语句和参数
        return invocation.proceed();
    }
}